<?php
/**
 * @Name
 * @Description
 * @Author 峰峰剥壳
 * @Date 2022/3/11 15:56
 */

namespace app\admin\controller;

use think\facade\Db;
use think\Request;
use think\facade\View;
use think\captcha\facade\Captcha;

class Login
{
    public function login(Request $request)
    {
        if($request->isPost()){
            $captcha = $request->param('captcha','','trim');
            $username = $request->param('username','','trim');
            $password = $request->param('password','','trim');
            // 判断验证码是否正确
            if( !captcha_check($captcha ))
            {
                return json(['status' => 'fail','msg' => '验证码不正确']);
            }
            // 获取数据库中的用户
            $user = Db::name('admin')->where('username',$username)->find();

            if(!$user){
                return json(['status' => 'fail','msg' => '用户名不存在']);
            }
            if($user['password'] != md5($password)){
                return json(['status' => 'fail','msg' => '密码不正确']);
            }
            // 将用户名存入session
            session('username',$username);
            return json(['status' => 'success','msg' => '登陆成功']);
        }else{
            return View::fetch('login');
        }

    }
    // 验证码
    public function captcha()
    {
        return Captcha::create();
    }
    // 退出登录
    public function logout()
    {
        session('username',null);
        return json(['status'=>'success','msg'=>'退出登录成功']);
    }
}